package com.caoJun.transaction;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: SSM_homework
 * @Author 83-start
 * @Time 2021/4/22 12:33
 */
public class AccountDaoImpl implements AccountDao {
    /**
     * 转账操作
     *
     * @param outUser 汇款人
     * @param inUser  收款人
     * @param money   汇款金额
     */
    @Override
    public void xml_transfer(int outUser, int inUser, double money) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        com.caoJun.jdbcTemplate.AccountDaoImpl accountDao =
                context.getBean("accountDao", com.caoJun.jdbcTemplate.AccountDaoImpl.class);
        // 查询余额
        double use1balance = accountDao.selectBalanceById(outUser);
        double use2balance = accountDao.selectBalanceById(inUser);

        // 转账
        accountDao.updateBalance(outUser, use1balance - money);
        accountDao.updateBalance(inUser, use2balance + money);
    }

    /**
     * 基于 注解的事务管理 ——转账操作
     *
     * @param outUser 汇款人
     * @param inUser  收款人
     * @param money   汇款金额
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
    public void annotation_transfer(int outUser, int inUser, double money) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        com.caoJun.jdbcTemplate.AccountDaoImpl accountDao =
                context.getBean("accountDao", com.caoJun.jdbcTemplate.AccountDaoImpl.class);
        // 查询余额
        double use1balance = accountDao.selectBalanceById(outUser);
        double use2balance = accountDao.selectBalanceById(inUser);

        // 转账
        accountDao.updateBalance(outUser, use1balance - money);
        accountDao.updateBalance(inUser, use2balance + money);
    }
}
